<?php

namespace addons\qingdongams\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 * 请假表
 */
class Leave extends Model {
    use SoftDelete;
	// 表名,不含前缀
	protected $name = 'qingdongams_attendance_leave';
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = 'int';
	// 定义时间戳字段名
	protected $createTime = 'createtime';
	protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';


    public function getCreatetimeAttr($value) {
        return date('Y-m-d H:i:s', $value);
    }
    //创建人
    public function createStaff() {
        return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,img,post');
    }

    //创建请假单
    public static function createLeave($params) {
        $staff = Staff::info();
        if (!empty($staff)) {
            $params['create_staff_id'] = $staff->id;
        }

        $flow = Flow::getsteplist(Flow::LEAVE_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }
        $Model = new self;
        $result = $Model->allowField(true)->save($params);
        $lastId=$Model->id;
        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::LEAVE_STATUS, $lastId);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::LEAVE_TYPE, $lastId, $staff_id);
            }
        }


        return true;
    }

    /**
     * 获取
     */
    public function getFilesAttr($value, $data)
    {
        if (empty($data['file_ids'])) {
            return '';
        }
        $paths = File::where(['id' => ['in', $data['file_ids']]])->column('file_path');

        return implode(',', $paths);
    }
}
